package fr.p10.miage.gestionabsence.action;

import fr.p10.miage.gestionabsence.form.LoginActionForm;
import fr.p10.miage.gestionabsence.model.EtudiantBDD;
import fr.p10.miage.gestionabsence.model.IntervenantBDD;
import fr.p10.miage.gestionabsence.model.SessionUtilisateur;
import fr.p10.miage.gestionabsence.model.Utilisateur;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Sofian Seid
 */
public class LoginAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private static final String FAIL = "Index";

    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.sql.SQLException
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws  SQLException, Exception {
        
        ActionErrors errors = new ActionErrors();
        LoginActionForm loginActionForm = (LoginActionForm) form;
        Utilisateur utilisateur= null;
        
        try {
            utilisateur = IntervenantBDD.trouverParLoginEtPassword(loginActionForm.getLogin(), loginActionForm.getPassword());
        } catch (Exception ex) {
            errors.add("compte", new ActionMessage("errors.invalid", " Identifiant/Mot de passe"));
        }
        
        try{
            utilisateur = EtudiantBDD.trouverParLoginEtPassword(loginActionForm.getLogin(), loginActionForm.getPassword());
        } catch (Exception ex) {
            errors.add("compte", new ActionMessage("errors.invalid", " Identifiant/Mot de passe"));
        }
        
        if (utilisateur==null){
            if(!errors.isEmpty()){
                this.saveErrors(request, errors);
            }
            return mapping.findForward(LoginAction.FAIL);
        }
        else{
            SessionUtilisateur.login(request, utilisateur);
            return mapping.findForward("Accueil");
        }
    }
}